const cloud = require('wx-server-sdk')
cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database({});
const db_account = db.collection('db_account');

const MAX_LIMIT = 100
exports.main = async (event, context) => {
  const { OPENID } = cloud.getWXContext()
  // return db_account.where({
  //   _openid: OPENID
  // }).get();
  // 先取出集合记录总数
  const countResult = await db_account.count();
  const total = countResult.total;
  // 计算需分几次取
  const batchTimes = Math.ceil(total / MAX_LIMIT);
  // 承载所有读操作的 promise 的数组
  const tasks = [];
  for (let i = 0; i < batchTimes; i++) {
    const promise = db_account.skip(i * MAX_LIMIT).limit(MAX_LIMIT).where({
      _openid: OPENID
    }).get();
    tasks.push(promise);
  }

  // 等待所有
  return (await Promise.all(tasks)).reduce((acc, cur) => ({
    data: acc.data.concat(cur.data),
    errMsg: acc.errMsg
  }));
}